package com.woman.beautylive.data.repository;

import android.os.Build;
import android.util.Log;

import com.woman.beautylive.BuildConfig;
import com.woman.beautylive.data.bean.AnchoBean;
import com.woman.beautylive.data.bean.AnchorSummary;
import com.woman.beautylive.data.bean.BaseResponse;
import com.woman.beautylive.data.bean.CurrencyRankItem;
import com.woman.beautylive.data.bean.GetFriendBean;
import com.woman.beautylive.data.bean.HotAnchorPageBean;
import com.woman.beautylive.data.bean.HotAnchorSummary;
import com.woman.beautylive.data.bean.IncomeBean;
import com.woman.beautylive.data.bean.LoginInfo;
import com.woman.beautylive.data.bean.PageBean;
import com.woman.beautylive.data.bean.PushStreamInfo;
import com.woman.beautylive.data.bean.ThemBean;
import com.woman.beautylive.data.bean.ThirdLoginPlatform;
import com.woman.beautylive.data.bean.gift.Gift;
import com.woman.beautylive.data.bean.me.PlayBackInfo;
import com.woman.beautylive.data.bean.me.UserInfo;
import com.woman.beautylive.data.bean.room.HitList;
import com.woman.beautylive.data.bean.room.LiveRoomEndInfo;
import com.woman.beautylive.data.bean.room.RoomAdminInfo;
import com.woman.beautylive.data.bean.transaction.PresentRecordItem;
import com.woman.beautylive.data.bean.transaction.RechargeInfo;
import com.woman.beautylive.data.bean.transaction.WithDrawRespose;
import com.woman.beautylive.domain.LocalDataManager;
import com.woman.beautylive.presentation.ui.main.find.paihangbangbean.DongTaiDetailBean;
import com.woman.beautylive.presentation.ui.main.find.paihangbangbean.DongTaiListBean;
import com.woman.beautylive.presentation.ui.main.find.paihangbangbean.MeiLiBangBean;
import com.woman.beautylive.presentation.ui.main.find.paihangbangbean.MyDongTaiBean;
import com.woman.beautylive.presentation.ui.main.find.pengyouquan.PublishBean;
import com.woman.beautylive.util.Const;
import com.woman.beautylive.util.L;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Observable;

/**
 * 使用Retrofit实现的网络请求。
 * Created by huanzhang on 2016/4/11.
 */
public class NewRetrofitSource implements ISource {
    private static final int CONNECT_TIME_OUT = 60;
    private static final int WRITE_TIME_OUT = 60;
    private static final int READ_TIME_OUT = 60;

    private RetrofitApi api;

    public NewRetrofitSource() {
        OkHttpClient okHttpClient = new OkHttpClient();
        OkHttpClient.Builder clientBuilder = okHttpClient.newBuilder()
                //添加通用请求信息, see http://stackoverflow.com/a/33667739
                .addNetworkInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Request request = chain.request();
                        HttpUrl.Builder builder = request.url().newBuilder()
                                .addQueryParameter("device", Build.MODEL);
                        //存在可能取不到Token的情况，所以只在有信息的时候调用getToken，否则传空。
                        LoginInfo loginInfo = LocalDataManager.getInstance().getLoginInfo();
                        builder.addQueryParameter("token", loginInfo != null ? loginInfo
                                .getToken() : "");
                        request = request.newBuilder().url(builder.build()).build();
                        return chain.proceed(request);
                    }
                })
                .connectTimeout(CONNECT_TIME_OUT, TimeUnit.SECONDS)
                .writeTimeout(WRITE_TIME_OUT, TimeUnit.SECONDS)
                .readTimeout(READ_TIME_OUT, TimeUnit.SECONDS)
                .retryOnConnectionFailure(true);

        if (BuildConfig.DEBUG) {
            HttpLoggingInterceptor logging = new HttpLoggingInterceptor(L.INSTANCE);
            logging.setLevel(HttpLoggingInterceptor.Level.BODY);
            clientBuilder.addNetworkInterceptor(logging);
        }

        okHttpClient = clientBuilder.build();

        Retrofit mRetrofit = new Retrofit.Builder()
                .baseUrl(Const.NEW_URL)
                .client(okHttpClient)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        api = mRetrofit.create(RetrofitApi.class);
    }

    @Override
    public Observable<BaseResponse<LoginInfo>> register(String username, String password) {
        return api.register(username, password);
    }

    @Override
    public Observable<BaseResponse<LoginInfo>> autoLogin(String token) {
        return api.autoLogin(token);
    }

    @Override
    public Observable<BaseResponse<LoginInfo>> login(String username, String password) {
        return api.login(username, password);
    }

    @Override
    public Observable<BaseResponse<PageBean<AnchorSummary>>> queryAnchors(String condition, int
            pageNum) {
        return api.queryAnchors(condition, pageNum);
    }

    @Override
    public Observable<BaseResponse<List<HotAnchorSummary>>> loadFollowedLives(int pageNum) {
        return api.loadFollowedLives(pageNum);
    }


    @Override
    public Observable<BaseResponse<List<HotAnchorSummary>>> loadTopicLives(int topicID) {
        return api.loadTopicLives(topicID);
    }

    @Override
    public Observable<BaseResponse<HotAnchorPageBean>> loadHotAnchors(int pageNum) {
        return api.meiLiBang(pageNum);
    }

    @Override
    public Observable<BaseResponse<HotAnchorPageBean>> loadHotAnchors(String token,String city,String sex) {
        return api.meiLiBang(token, city, sex);
    }

    @Override
    public Observable<BaseResponse<Object>> followAnchor(String uid) {
        return api.followAnchor(uid);
    }

    @Override
    public Observable<BaseResponse<Object>> unfollowAnchor(String uid) {
        return api.unfollowAnchor(uid);
    }

    @Override
    public Observable<BaseResponse<UserInfo>> getUserInfo(Integer uid) {
        return api.getUserInfo(uid);
    }

    @Override
    public Observable<BaseResponse<String>> getEmotion(String token,int emotion) {
        return api.getEmotion(token, emotion);
    }

    @Override
    public Observable<BaseResponse<String>> setBirthday(String token,String birthday) {
        return api.setBirthday(token, birthday);
    }

    @Override
    public Observable<BaseResponse<String>> getProvince(String token,String province,String city) {
        return api.getProvince(token, province, city);
    }


    @Override
    public Observable<BaseResponse<AnchoBean>> getAnchoBean(String user_id) {
        return api.getAnchoBean(user_id);
    }

    @Override
    public Observable<BaseResponse<String>> starUser(String token,String uid,String roomid) {
        return api.starUser(token, uid, roomid);
    }

    @Override
    public Observable<BaseResponse<String>> unStarUser(String token,String uid,String roomid) {
        return api.unStarUser(token, uid, roomid);
    }

    @Override
    public Observable<BaseResponse<PageBean<AnchorSummary>>> getUserStars(String uid, int pageNum) {
        return api.getUserStars(uid, pageNum);
    }

    @Override
    public Observable<BaseResponse<PageBean<AnchorSummary>>> getUserFans(String uid, int pageNum) {
        return api.getUserFans(uid, pageNum);
    }

    @Override
    public Observable<BaseResponse<PageBean<AnchorSummary>>> loadRecommendAnchors(String token,String time) {
        return api.loadRecommendAnchors(token, time);
    }

    @Override
    public Observable<BaseResponse<PageBean<AnchorSummary>>> loadCommendAnchors(String token,String city) {
        return api.loadCommendAnchors(token, city);
    }

    @Override
    public Observable<BaseResponse<List<Gift>>> getAvailableGifts() {
        return api.getAvailableGifts();
    }

    @Override
    public Observable<BaseResponse<Object>> sendGift(String toUserId, String giftId, int count) {
        return api.sendGift(toUserId, giftId, count);
    }

    @Override
    public Observable<BaseResponse<Object>> sendHongBaoGift(String token, String roomuid, String giftid) {
        return api.sendHongBaoGift(token, roomuid, giftid);
    }


    @Override
    public Observable<BaseResponse<String>> editProfile(String profileJson) {
        return api.editProfile(profileJson);
    }

    @Override
    public Observable<BaseResponse<String>> editJob(String token,String professional) {
        return api.editJob(token, professional);
    }

    @Override
    public Observable<BaseResponse<Object>> setLiveStatus(String token,String status) {
        return api.setLiveStatus(token, status);
    }

    @Override
    public Observable<BaseResponse<LiveRoomEndInfo>> getLiveRoomInfo(String roomId) {
        return api.getLiveRoomInfo(roomId);
    }

    @Override
    public Observable<BaseResponse<RechargeInfo>> getRechargeMap() {
        return api.getRechargeInfo();
    }

    @Override
    public Observable<BaseResponse<Object>> reportLocation(String lat, String lng) {
        return api.reportLocation(lat, lng);
    }

    @Override
    public Observable<BaseResponse<PageBean<CurrencyRankItem>>> getCurrencyRankList(String uid, int page) {
        return api.getCurrencyRankList(uid, page);
    }

    @Override
    public Observable<BaseResponse<String>> uploadAvatar(String path) {
        File file = new File(path);
        RequestBody photoRequestBody = RequestBody.create(MediaType.parse("image/jpg"), file);
        MultipartBody.Part photoPart = MultipartBody.Part.createFormData("name", file.getName(),
                photoRequestBody);
        return api.uploadAvatar(photoPart);
//        return api.editProfile(path);
    }

    @Override
    public Observable<BaseResponse<IncomeBean>> getIncomeBean() {
        return api.getIncomeBean();
    }

    @Override
    public Observable<BaseResponse<WithDrawRespose>> withDraw(String num, String account) {
        return api.withDraw(num, account);
    }

    @Override
    public Observable<BaseResponse<List<PresentRecordItem>>> getPresentRecord() {
        return api.getPresentRecord();
    }

    @Override
    public Observable<BaseResponse<LoginInfo>> thirdLogin(String openId, @ThirdLoginPlatform String platform, String extras) {
        return api.thirdLogin(openId, platform, extras);
    }

    @Override
    public Observable<BaseResponse<String>> generateRechargeOrder(String amount) {
        return api.generateRechargeOrder(amount);
    }

    @Override
    public Observable<BaseResponse<PushStreamInfo>> generatePushStreaming(String roomId) {
        return api.generatePushStreaming(roomId);
    }

    @Override
    public Observable<BaseResponse<String>> getPlaybackUrl(String roomId) {
        return api.getPlaybackUrl(roomId);
    }

    @Override
    public Observable<BaseResponse<String>> sendCaptcha(String phone) {
        return api.sendCaptcha(phone);
    }

    @Override
    public Observable<BaseResponse<List<RoomAdminInfo>>> getAdmin(String token, String anchorid) {
        return api.getAdmin(token, anchorid);
    }

    @Override
    public Observable<BaseResponse<Object>> removeAdmin(String token, String anchorid,String adminid) {
        return api.removeAdmin(token, anchorid, adminid);
    }

    @Override
    public Observable<BaseResponse<List<PlayBackInfo>>> getPlayBack(String token,String roomID) {
        Log.i("mrl","RetrofitSource ");
        return api.getPlayBack(token, roomID);
    }

    @Override
    public Observable<BaseResponse<String>> getPlayBackListUrl(String roomID, String start, String end) {
        Log.i("mrl","RetrofitSource1");
        return api.getPlayBackListUrl(roomID, start, end);
    }

//    得到话题对象
    @Override
    public Observable<BaseResponse<ThemBean>> getThemBean() {
        Log.i("mrl",api.getThemBean()+"有问题吗");
        return api.getThemBean();
    }

    //    传递房间号
    @Override
    public Observable<BaseResponse<Object>> postCreatRoom(String token, String title,String roomid,String city,String province) {
        return api.postCreateRoom(token, title, roomid, city, province);
    }

    @Override
    public Observable<BaseResponse<List<HitList>>> getHitList(String token) {
        return api.hitList(token);
    }

    //    得到话题对象
    @Override
    public Observable<BaseResponse<ThemBean>> getThemBean(String title,String number) {
        return api.getThemBean(title, number);
    }

    @Override
    public Observable<BaseResponse<Object>> setHit(String token, String hitid) {
        return api.setHit(token, hitid);
    }

    @Override
    public Observable<BaseResponse<Object>> removeHit(String token, String hitid) {
        return api.removeHit(token, hitid);
    }

    @Override
    public Observable<BaseResponse<List<GetFriendBean>>> getFriendList() {
        return api.getFriendList();
    }

    @Override
    public Observable<BaseResponse<LoginInfo>> loginByCaptcha(String username, String captcha) {
        return api.loginByCaptcha(username, captcha);
    }

    @Override
     public Observable<BaseResponse<List<MeiLiBangBean>>> meilibang(int pageNum) {
        return api.meiLiBang();
    }

    @Override
    public Observable<BaseResponse<List<MeiLiBangBean>>> fuHaobang(int pageNum) {
        if(pageNum==0) {
            return api.meiLiBang();
        }else{
            return api.fuHaoBang();
        }
    }

    @Override
    public Observable<BaseResponse<PublishBean>> publish(String token, String content,String pics) {
        return api.publicsh(token, content, pics);
    }

    @Override
    public Observable<BaseResponse<String>> updatePublish(String token,String pid, String content,String pics) {
        return api.updatePublish(token, pid, content, pics);
    }

    @Override
    public Observable<BaseResponse<String>> deletePublish(String token, String pid) {
        return api.deletePublish(token, pid);
    }
    @Override
    public Observable<BaseResponse<PublishBean>> replyOne(String token, String pid,String content) {
        return api.replyOne(token, pid, content);
    }

    @Override
    public Observable<BaseResponse<String>> dianzan(String token, String pid, String isLike) {
        return api.dianzan(token, pid, isLike);
    }

    @Override
    public Observable<BaseResponse<PublishBean>> replyTwo(String token, String rid, String content) {
        return api.replyTwo(token, rid, content);
    }
    @Override
    public Observable<BaseResponse<DongTaiListBean>> dongTaiLieBiao(String token, String page, String pagesize) {
        return api.dongTaiLieBiao(token, page, pagesize);
    }

    @Override
    public Observable<BaseResponse<DongTaiDetailBean>> getDongTaiDetail(String token, String pid, String max_like, String max_reply) {
        return api.dongtaiDetail(token, pid, max_like, max_reply);
    }

    @Override
    public Observable<BaseResponse<String>> replyDelete(String token, String rid) {
        return api.replyDelete(token, rid);
    }

    @Override
    public Observable<BaseResponse<List<MyDongTaiBean>>> getMyDongTaiLieBiao(String token, String page, String pagesize) {
        return api.getMyDongTaiList(token, page, pagesize);
    }

    @Override
    public Observable<BaseResponse<DongTaiListBean.DongTaiItem.ReplyList>> getHuiFuList(String token,String pid, String page, String pagesize) {
        return api.huiFuList(token,pid, page, pagesize);
    }

    @Override
    public Observable<BaseResponse<DongTaiListBean.DongTaiItem.ReplyList>> getDianZanList(String token, String pid, String pageNo, String pageSize) {
        return api.dianzanList(token, pid, pageNo, pageSize);
    }

}
